package com.eat.dao.impl;

import com.eat.core.BaseDao;
import com.eat.dao.ItemDao;
import com.eat.domain.Item;
import com.sun.org.apache.bcel.internal.generic.NEWARRAY;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * Created by liufeiyang on 2018/4/17.
 */
public class ItemDaoImpl extends BaseDao implements ItemDao {
    //增加商品
    public int insert(Item item){
        String sql="INSERT INTO item (item_name,item_price,item_description,gmt_create) VALUES(?,?,?,?)";
        int num=super.update(sql,item.getItemName(),item.getItemPrice(),item.getItemDescription(),new Date());
        return num;
    }
    //根据商品编号删除商品
    public int delete(long itemId){
        String sql="DELETE FROM item WHERE item_id=?";
        int num=super.update(sql,itemId);
        return num;
    }
    //根据商品编号更改商品价格和描述
    public int update(Item item){
        String sql="UPDATE item SET item_price=? , item_description=? , gmt_modified=? WHERE item_id=?";
        int num=super.update(sql,item.getItemPrice(),item.getItemDescription(),new Date(),item.getItemId());
        return num;
    }
    //按编号查询一个商品
    public Item findOne(long itemId){
        String sql="SELECT * FROM item WHERE item_id=? ";
        ResultSet rst=super.executeQuery(sql,itemId);
        Item item=null;
        try {
            while (rst.next()){
            item=new Item(rst.getLong("item_id"),rst.getString("item_name"),rst.getBigDecimal("item_price"),rst.getString("item_description"),
            rst.getDate("gmt_create"),rst.getDate("gmt_modified"));
            }
            super.release();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return item;
    }
    //查询所有商品
    public List<Item> findAll(){
        List<Item> itemList= new ArrayList<>();
        String sql="SELECT * FROM item";
        ResultSet rst=super.executeQuery(sql);
        try {
            while(rst.next()){
        Item item=new Item(rst.getLong("item_id"),rst.getString("item_name"),rst.getBigDecimal("item_price"),rst.getString("item_description"),
        rst.getDate("gmt_create"),rst.getDate("gmt_modified"));
        itemList.add(item);
            }
        super.release();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return itemList;
    }
}
